from datetime import date
import datetime

from rest_framework.generics import ListAPIView
from apps.goods.models import GoodsVisitCount
from apps.meiduo_admin.serializers.statcistical import GoodsVisitCountSerializer
from apps.users.models import User
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAdminUser, IsAuthenticated


# 用户总数
class UserTotalCountView(APIView):
    # 管理员权限
    permission_classes = [IsAuthenticated]

    def get(self, request):
        # 获取当前日期
        now_date = date.today()
        # 获取所有用户总数
        count = User.objects.all().count()
        return Response({
            'count': count,
            'date': now_date
        })


# 日活用户数量
class UserDailyActiveCountView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        today = date.today()
        count = User.objects.filter(last_login__gte=today).count()
        return Response({
            "count": count,
            "date": today
        })

# 日增用户数量
class UserDailyAddView(APIView):
    permission_classes = [IsAuthenticated]
    def get(self, request):
        today = date.today()
        count = User.objects.filter(date_joined__gte=today).count()
        return Response({
            "count": count,
            "date": today
        })


# 日下单用户数量
class UserDailyOrderCountView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        today = date.today()
        count = User.objects.filter(orderinfo__create_time__gte=today).count()
        return Response({
            "count": count,
            "date": today
        })


# 月增用户数量
class UserMonthCountView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        # 一个月前的第一天日期
        month_start_day = date.today() - datetime.timedelta(days=30)

        # 获取30天的数据 建立列表进行存放
        data = []
        # 遍历存储
        for i in range(30):
            start_day = month_start_day + datetime.timedelta(days=i)
            end_day = month_start_day + datetime.timedelta(days=i+1)
            count = User.objects.filter(date_joined__gte=start_day, date_joined__lt=end_day).count()
            data.append({
                "count": count,
                "date": start_day
            })
        return Response(data)


# 日分类商品访问量统计
class UserCategoryCountAPIView(ListAPIView):
    permission_classes = [IsAuthenticated]
    queryset = GoodsVisitCount.objects.filter(date=date.today())
    serializer_class = GoodsVisitCountSerializer

